package com.cjgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjgl.common.BaseResponse;
import com.cjgl.common.ErrorCode;
import com.cjgl.common.ResultUtils;
import com.cjgl.exception.BusinessException;
import com.cjgl.model.dto.score.SelectScoresByTermOrCourseNameREquest;
import com.cjgl.model.dto.student.StuRequestChangePassword;
import com.cjgl.model.entity.*;
import com.cjgl.model.vo.clsss.ClassVo;
import com.cjgl.model.vo.courseTable.CourseTableVo;
import com.cjgl.model.vo.scores.ScoresVo;
import com.cjgl.model.vo.student.StudentAndClazzInfoVo;
import com.cjgl.model.vo.student.StudentInfoVo;
import com.cjgl.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.cjgl.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author zhangyuwu
 */
@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController {
	@Resource
	TblStudentsService studentsService;
	@Resource
	TblClassService classService;
	@Resource
	TblScoresService scoresService;
	@Resource
	TblCoursestableService coursestableService;

	@Resource
	TblCoursesService coursesService;

	@Resource
	TblUsersService usersService;
	@Resource
	TblTeacherService teacherService;


	/**
	 * 获取学生自己信息
	 *
	 * @param request
	 * @return
	 */
	@GetMapping("/getSelfInfo")
	public BaseResponse<Object> getSelfInfo(HttpServletRequest request) {
		TblStudents student = (TblStudents) request.getSession().getAttribute(USER_LOGIN_STATE);
		if (student == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}
		String studentNo = student.getStudentNo();
		log.info("查询自己的信息--->" + studentNo);

		//查学生信息
		LambdaQueryWrapper<TblStudents> studentWrapper = new LambdaQueryWrapper<>();
		studentWrapper.select().eq(TblStudents::getStudentNo, studentNo);
		TblStudents studentInfo = studentsService.getBaseMapper().selectOne(studentWrapper);


		//没查到（应该是不会的）
		StudentInfoVo studentInfoVo = new StudentInfoVo();
		if (ObjectUtils.isEmpty(studentInfo)) {
			return ResultUtils.success(studentInfoVo);
		}

		studentInfoVo.setId(studentInfo.getId());
		studentInfoVo.setStudentNo(studentInfo.getStudentNo());
		studentInfoVo.setStudentName(studentInfo.getStudentName());
		studentInfoVo.setStudentGender(studentInfo.getStudentGender());
		studentInfoVo.setStudentAddress(studentInfo.getStudentAddress());
		studentInfoVo.setStudentBirthdate(studentInfo.getStudentBirthdate());
		studentInfoVo.setStudentMajor(studentInfo.getStudentMajor());
		studentInfoVo.setStudentClassNo(studentInfo.getStudentClassNo());
		studentInfoVo.setStudentEnrollmentDate(studentInfo.getStudentEnrollmentDate());
		studentInfoVo.setStudentAcademicDuration(studentInfo.getStudentAcademicDuration());
		studentInfoVo.setStudentStatus(studentInfo.getStudentStatus());
		studentInfoVo.setStudentRemarks(studentInfo.getStudentRemarks());
		log.info(studentInfo.toString());

		return ResultUtils.success(studentInfoVo);
	}


	/**
	 * 获取班级信息
	 *
	 * @param request
	 * @return
	 */
	@GetMapping("/getClassInfo")
	public BaseResponse<Object> getClassInfo(HttpServletRequest request) {
		TblStudents student = (TblStudents) request.getSession().getAttribute(USER_LOGIN_STATE);

		if (student == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}

		String studentClassNo = student.getStudentClassNo();
		String studentNo = student.getStudentNo();
		log.info("查询自己的班级信息--->" + studentNo);
		//查班级信息
		LambdaQueryWrapper<TblClass> clazzWrapper = new LambdaQueryWrapper<>();
		clazzWrapper.eq(TblClass::getClassNo, studentClassNo);
		TblClass aClass = classService.getOne(clazzWrapper);

		ClassVo classVo = new ClassVo();
		classVo.setId(aClass.getId());
		classVo.setClassNo(aClass.getClassNo());
		classVo.setClassName(aClass.getClassName());
		classVo.setClassMajor(aClass.getClassMajor());
		classVo.setClassPersonNum(aClass.getClassPersonNum());
		classVo.setClassDate(aClass.getClassDate());
		classVo.setClassTeacherName(aClass.getClassTeacherName());
		classVo.setClassStatus(aClass.getClassStatus());
		return ResultUtils.success(classVo);
	}


	/**
	 * 获取成绩
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/getScoresInfo")
	public BaseResponse<Object> getScoresInfo(@RequestBody SelectScoresByTermOrCourseNameREquest term, HttpServletRequest request) {
		TblStudents student = (TblStudents) request.getSession().getAttribute(USER_LOGIN_STATE);
		if (student == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}
		String year = term.getYear() != null ? term.getYear() : "";
		String ter = term.getTer() != null ? term.getTer() : "";
		String termSelect = "";
		termSelect = year + ter;
		// 学号 和学期（学期模糊查询）
		String studentNo = student.getStudentNo();

		//查成绩信息
		LambdaQueryWrapper<TblScores> scoreWrapper = new LambdaQueryWrapper<>();
		scoreWrapper
				.eq(TblScores::getStudentNo, studentNo)
				.like(!StringUtils.isEmpty(termSelect), TblScores::getTerm, termSelect);

		List<TblScores> scoreInfos = scoresService.getBaseMapper().selectList(scoreWrapper);
		log.info(scoreInfos.toString());
		if (scoreInfos.isEmpty() || scoreInfos == null) {
			scoreInfos = new ArrayList<>();
		}

		List<ScoresVo> scoresVoCollect = scoreInfos.stream().map(item -> {
			String courseNo = item.getCourseNo();

			//查课程名
			LambdaQueryWrapper<TblCourses> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(TblCourses::getCourseNo, courseNo);
			TblCourses course = coursesService.getBaseMapper().selectOne(queryWrapper);

			//放进vo
			ScoresVo scoresVo = new ScoresVo();
			scoresVo.setCourseName(course.getCourseName());
			scoresVo.setStudentNo(item.getStudentNo());
			scoresVo.setScore(item.getScore());
			scoresVo.setTerm(item.getTerm());
			return scoresVo;
		}).collect(Collectors.toList());

		return ResultUtils.success(scoresVoCollect);
	}


	/**
	 * 获取课程表信息
	 *
	 * @param request
	 * @return
	 */
	@PostMapping ("/getCoursetableInfo")
	public BaseResponse<Object> getCoursetableInfo(@RequestBody SelectScoresByTermOrCourseNameREquest term, HttpServletRequest request) {
		TblStudents student = (TblStudents) request.getSession().getAttribute(USER_LOGIN_STATE);
		if (student == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}


		String year = term.getYear() != null ? term.getYear() : "";
		String ter = term.getTer() != null ? term.getTer() : "";
		String termSelect = "";
		termSelect = year + ter;


		String studentClassNo = student.getStudentClassNo();
		LambdaQueryWrapper<TblCoursestable> courseWrapper = new LambdaQueryWrapper<>();
		courseWrapper
				.eq(TblCoursestable::getClassNo, studentClassNo)
				.like(!StringUtils.isEmpty(termSelect), TblCoursestable::getTerm, termSelect);

		List<TblCoursestable> coursestables = coursestableService.getBaseMapper().selectList(courseWrapper);

		if (coursestables.isEmpty() || coursestables == null) {
			coursestables = new ArrayList<>();
		}

		//放老师姓名
		List<CourseTableVo> courseTableCollect = coursestables.stream().map(item -> {
			String courseNo = item.getCourseNo();
			String teacherNo = item.getTeacherNo();

			//查课程名
			LambdaQueryWrapper<TblCourses> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.select(TblCourses::getCourseName).eq(TblCourses::getCourseNo, courseNo);
			TblCourses course = coursesService.getBaseMapper().selectOne(queryWrapper);

			//查老师名
			LambdaQueryWrapper<TblTeacher> teaQueryWrapper = new LambdaQueryWrapper<>();
			teaQueryWrapper.select(TblTeacher::getTeacherName).eq(TblTeacher::getTeacherNo, teacherNo);
			TblTeacher teacher = teacherService.getBaseMapper().selectOne(teaQueryWrapper);

			//放进CourseTableVo
			CourseTableVo courseTableVo = new CourseTableVo();
			courseTableVo.setCourseName(course.getCourseName());
			courseTableVo.setTeacherName(teacher.getTeacherName());
			courseTableVo.setClassNo(item.getClassNo());
			courseTableVo.setPlace(item.getPlace());
			courseTableVo.setTeachingTime(item.getTeachingTime());
			courseTableVo.setTerm(item.getTerm());
			courseTableVo.setCoursestableId(item.getCoursestableId());

			return courseTableVo;

		}).collect(Collectors.toList());

		return ResultUtils.success(courseTableCollect);
	}


	/**
	 * 获取基本信息,班级信息,课程信息(包含成绩)
	 */
	@GetMapping
	public BaseResponse<Object> getClassCourseScoreInfo(HttpServletRequest request) {
		TblStudents student = (TblStudents) request.getSession().getAttribute(USER_LOGIN_STATE);

		if (student == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}
		String studentNo = student.getStudentNo();

		log.info("查询学号的所有信息--->" + studentNo);
		StudentAndClazzInfoVo studentAndClazzInfoVo = new StudentAndClazzInfoVo();

		//查学生信息
		LambdaQueryWrapper<TblStudents> studentWrapper = new LambdaQueryWrapper<>();
		studentWrapper.select().eq(TblStudents::getStudentNo, studentNo);
		TblStudents studentsInfo = studentsService.getBaseMapper().selectOne(studentWrapper);
		log.info(studentsInfo.toString());
		studentAndClazzInfoVo.setStudent(studentsInfo);

		//查班级信息
		LambdaQueryWrapper<TblClass> clazzWrapper = new LambdaQueryWrapper<>();
		clazzWrapper.select().eq(TblClass::getClassNo, studentsInfo.getStudentClassNo());
		TblClass clazzInfo = classService.getOne(clazzWrapper);
		if (clazzInfo == null) {
			clazzInfo = new TblClass();
		}
		log.info(clazzInfo.toString());
		studentAndClazzInfoVo.setClazz(clazzInfo);

		//查成绩信息
		LambdaQueryWrapper<TblScores> scoreWrapper = new LambdaQueryWrapper<>();
		scoreWrapper.select().eq(TblScores::getStudentNo, studentsInfo.getStudentNo());
		List<TblScores> scoreInfos = scoresService.getBaseMapper().selectList(scoreWrapper);
		log.info(scoreInfos.toString());
		if (scoreInfos.isEmpty() || scoreInfos == null) {
			scoreInfos = new ArrayList<>();
		}

		List<ScoresVo> scoresVoCollect = scoreInfos.stream().map(item -> {
			String courseNo = item.getCourseNo();

			//查课程名
			LambdaQueryWrapper<TblCourses> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(TblCourses::getCourseNo, courseNo);
			TblCourses course = coursesService.getBaseMapper().selectOne(queryWrapper);

			//放进vo
			ScoresVo scoresVo = new ScoresVo();
			scoresVo.setCourseName(course.getCourseName());
			scoresVo.setStudentNo(item.getStudentNo());
			scoresVo.setScore(item.getScore());
			scoresVo.setTerm(item.getTerm());
			return scoresVo;
		}).collect(Collectors.toList());
		studentAndClazzInfoVo.setScores(scoresVoCollect);

		//查课程表信息
		LambdaQueryWrapper<TblCoursestable> courseWrapper = new LambdaQueryWrapper<>();
		courseWrapper.select().eq(TblCoursestable::getClassNo, clazzInfo.getClassNo());
		List<TblCoursestable> courseTableInfos = coursestableService.getBaseMapper().selectList(courseWrapper);
		if (courseTableInfos.isEmpty() || courseTableInfos == null) {
			courseTableInfos = new ArrayList<>();
		}
		List<CourseTableVo> courseTableCollect = courseTableInfos.stream().map(item -> {
			String courseNo = item.getCourseNo();
			String teacherNo = item.getTeacherNo();

			//查课程名
			LambdaQueryWrapper<TblCourses> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.select(TblCourses::getCourseName).eq(TblCourses::getCourseNo, courseNo);
			TblCourses course = coursesService.getBaseMapper().selectOne(queryWrapper);

			//查老师名
			LambdaQueryWrapper<TblTeacher> teaQueryWrapper = new LambdaQueryWrapper<>();
			teaQueryWrapper.select(TblTeacher::getTeacherName).eq(TblTeacher::getTeacherNo, teacherNo);
			TblTeacher teacher = teacherService.getBaseMapper().selectOne(teaQueryWrapper);

			//放进CourseTableVo
			CourseTableVo courseTableVo = new CourseTableVo();
			courseTableVo.setCourseName(course.getCourseName());
			courseTableVo.setTeacherName(teacher.getTeacherName());
			courseTableVo.setClassNo(item.getClassNo());
			courseTableVo.setPlace(item.getPlace());
			courseTableVo.setTeachingTime(item.getTeachingTime());
			courseTableVo.setTerm(item.getTerm());
			courseTableVo.setCoursestableId(item.getCoursestableId());

			return courseTableVo;

		}).collect(Collectors.toList());

		studentAndClazzInfoVo.setCoursestables(courseTableCollect);

		//因为当前面的查询都空时进行了处理，所以此处直接调用success
		return ResultUtils.success(studentAndClazzInfoVo);
	}


	@GetMapping("/getSameClassStudentsInfo")
	public BaseResponse<List<TblStudents>> getSameClassStudentsInfo(HttpServletRequest request) {
		TblStudents student = (TblStudents) request.getSession().getAttribute(USER_LOGIN_STATE);

		if (student == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}

		List<TblStudents> sameClassStudentsInfo = studentsService.getSameClassStudentsInfo(student.getStudentClassNo());

		return ResultUtils.success(sameClassStudentsInfo);
	}

	/**
	 * 修改学生的登陆密码
	 * (去user表修改)
	 */
	@PatchMapping
	public BaseResponse<Boolean> changeStudentPassword(@RequestBody StuRequestChangePassword stuRequestChangePassword, HttpServletRequest request) {


		TblStudents studentsIsLogin = (TblStudents) request.getSession().getAttribute(USER_LOGIN_STATE);
		if (studentsIsLogin == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}

		String studentPassword = stuRequestChangePassword.getStudentPassword();
		String studentNo = stuRequestChangePassword.getStudentNo();

		if (StringUtils.isAllEmpty(studentPassword, studentNo)) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		//返回是否修改密码成功 true 成功/false 失败
		Integer isChanged = usersService.changeUserPassword(studentNo, studentPassword);
		if (isChanged > 0) {
			return ResultUtils.success(true);

		}
		return ResultUtils.success(false);
	}
}
